package cn.bonoon.services.plugins;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.bonoon.core.plugins.ScheduleService;
import cn.bonoon.entities.calendars.ScheduleEntity;
import cn.bonoon.kernel.support.IOperator;
import cn.bonoon.kernel.support.services.AbstractService;

@Service
@Transactional(readOnly = true)
public class ScheduleServiceImpl extends AbstractService<ScheduleEntity> implements ScheduleService {

	@Override
	public List<ScheduleEntity> getByExecuteAt(IOperator opt, Date executeAt) {
		return __list(ScheduleEntity.class, "from ScheduleEntity x where x.creatorId=? and x.executeAt=?", opt.getId(), executeAt);
	}

	@Override
	public boolean hasSchedule(IOperator opt, Date executeAt) {
		return __exsit("select count(*) from ScheduleEntity x where x.creatorId=? and x.executeAt=?", opt.getId(), executeAt);
	}

	@Override
	public List<ScheduleEntity> getYear(IOperator opt, int year) {
		Calendar cal = Calendar.getInstance();
		cal.set(year, 1, 1, 0, 0, 0);
		Date dStart = cal.getTime();
		cal.add(Calendar.YEAR, 1);
		Date dEnd = cal.getTime();
		return __list(ScheduleEntity.class, "from ScheduleEntity x where x.creatorId=? and x.executeAt>=? and x.executeAt<?", opt.getId(), dStart, dEnd);
	}

	@Override
	@Transactional
	public void delete(IOperator opt, Long[] ids) {
		if (null != ids && ids.length != 0) {
			for (Long id : ids) {
				ScheduleEntity entity = __get(id);
				entityManager.remove(entity);
			}
		}
	}

	@Override
	public List<ScheduleEntity> getMonth(IOperator opt, int year, int month) {
		Calendar cal = Calendar.getInstance();
		cal.set(year, month, 1, 0, 0, 0);
		Date dStart = cal.getTime();
		cal.add(Calendar.MONTH, 1);
		Date dEnd = cal.getTime();
		return __list(ScheduleEntity.class, "from ScheduleEntity x where x.creatorId=? and x.executeAt>=? and x.executeAt<?", opt.getId(), dStart, dEnd);
	}

	@Override
	public List<ScheduleEntity> getWeek(IOperator opt, int year, int month, int date) {
		Calendar cal = Calendar.getInstance();
		cal.set(year, month, date, 0, 0, 0);
		int week = cal.get(Calendar.DAY_OF_WEEK);
		cal.add(Calendar.DATE, 1 - week); // 星期日
		Date dStart = cal.getTime();
		cal.add(Calendar.DATE, 7); // 下星期日
		Date dEnd = cal.getTime();
		return __list(ScheduleEntity.class, "from ScheduleEntity x where x.creatorId=? and x.executeAt>=? and x.executeAt<?", opt.getId(), dStart, dEnd);
	}

}
